#include "stdlib.h"
#include "string.h"
#include <hidef.h> /* for EnableInterrupts macro */
#include "Headers/derivative.h" /* include peripheral declarations */
#include "Headers/define.h"
#include "Headers/GPIO.h"
#include "Headers/SPI.h"
#include "Headers/ICG.h"
#include "Headers/micelaneous.h"
#include "Headers/RF.h"
#include "Headers/time.h"
#include "Headers/ADC.h"
#include "Headers/tinaco.h"

char tinaco(void){
  char error_adc, *send_adc, *command_rx, rta_fc = 0, *aux, *error;
  int x = 0;
  word adc;
  send_adc = malloc(50);
  command_rx = malloc(50);
  //delay_ms(100);
  error_adc = read_single_adc(5, &adc);
  if(!error_adc){
    adc &= 0xfffc;
    adc = adc >> 2;
    send_adc[0] = adc & 0x00ff;
    send_adc[1] = '|';
    send_adc[2] = 't';
    send_adc[3] = 'i';
    send_adc[4] = 'n';
    send_adc[5] = 'a';
    send_adc[6] = 'c';
    send_adc[7] = 'o';
    send_adc[8] = '|';
    send_adc[9] = 0;
    *command_rx = 0;
    while(strcmp(command_rx,"") == 0 && x < 200){
       if(!TX_pkt_rf(send_adc)){
        if(!RX_pkt_rf(command_rx)){
         if(strcmp(command_rx,"") != 0){
          aux = strtok(command_rx , "|");
          aux = strtok(NULL, "|");
          error = strcpy(command_rx , aux);
          if(strcmp(command_rx,"regadera") != 0)*command_rx = 0;
         }else *command_rx = 0; 
        }else *command_rx = 0;
       }else *command_rx = 0;
       __RESET_WATCHDOG();
       x++;
    }
    if(x >= 1000)rta_fc = 1;
  }else rta_fc = 1;
  free(send_adc);
  free(command_rx);
  ld4 = 0;
  delay_ms(100);
  ld4 = 1;
  return rta_fc;
}